package com.kyang.musiconline.controller;

import com.kyang.musiconline.model.ResponseData;
import com.kyang.musiconline.model.User;
import com.kyang.musiconline.model.Vinyl;
import com.kyang.musiconline.service.UserService;
import com.kyang.musiconline.service.VinylService;
import com.kyang.musiconline.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author kyang
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private VinylService vinylService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseData register(User user) {
        boolean isSuccess = userService.register(user);
        return new ResponseData(200, isSuccess, "success", "");
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseData login(String account, String password) {
        User user = userService.login(account, password);
        ResponseData responseData;
        if (user != null) {
            String token = JwtUtil.getToken(user);
            responseData = new ResponseData(200, true, "success", token);
        } else {
            responseData = new ResponseData(201, false, "User is not exist", "");
        }
        return responseData;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseData update(User user) {
        boolean isSuccess = userService.editItem(user);
        return new ResponseData(200, isSuccess, "success", "");
    }

    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public ResponseData userInfo() {
        String userId = JwtUtil.getCurrentUserId();
        User user = userService.getInfoById(userId);
        ResponseData responseData;
        if (user != null) {
            responseData = new ResponseData(200, true, "success", user);
        } else {
            responseData = new ResponseData(201, false, "User is not exist", "");
        }
        return responseData;
    }

    @RequestMapping(value = "/vinylInfo", method = RequestMethod.GET)
    public ResponseData vinylInfo() {
        String userId = JwtUtil.getCurrentUserId();
        List<Vinyl> list = vinylService.getUserVinyl(userId);
        ResponseData responseData;
        if (list != null && !list.isEmpty()) {
            responseData = new ResponseData(200, true, "success", list);
        } else {
            responseData = new ResponseData(201, false, "User is not exist", "");
        }
        return responseData;
    }
}
